package com.twoGroup.boot.controller;

import com.twoGroup.boot.pojo.*;
import com.twoGroup.boot.service.CommonService;
import com.twoGroup.boot.service.MerchantService;
import com.twoGroup.boot.utils.CommonUtils;
import com.twoGroup.boot.utils.MerchantUtils;

import com.twoGroup.boot.utils.QiniuCloudUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName
 * @Description TODO
 * @Author Xuyujie
 * @Date 2021/5/15 8:26
 * @Version 1.0
 **/
@Controller
@RequestMapping(value = "Merchant")
@Api(tags = "商家接口")
public class MerchantController {
    public static Logger logger = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CommonService commonService;
    private QiniuCloudUtil qiniuCloudUtil=new QiniuCloudUtil();

    //商家开店------->已经实现
    @ApiOperation(value = "商家开店")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopName", value = "限10个字符，支持中英文、数字、减号或下划线", required = true),
            @ApiImplicitParam(name = "userId", value = "用户名称", required = true),
    }
    )
    @GetMapping("addShop")
    @ResponseBody
    public ResultDate addShop(String shopName, String userId) {
        if (MerchantUtils.judgeLength(shopName, shopName.length())) {
            if (!merchantService.judgeShopName(shopName)) {
                ResultDate resultDate=ResultDate.fail("店铺已经存在！");
                return resultDate;
            } else if (!CommonUtils.isNumeric(userId)||!CommonUtils.isNotnull(userId)) {
                ResultDate resultDate=ResultDate.fail("用户信息有误！");
                return resultDate;
            } else if(merchantService.queryForUserShop(Integer.parseInt(userId))>=5){
                ResultDate resultDate=ResultDate.fail("用户已达最大开店量!");
                return resultDate;
            }else {
                Shop shop = new Shop(null, shopName, 0, Integer.parseInt(userId));
                int i = merchantService.addShop(shop);
                if(i>0){
                    ResultDate resultDate=ResultDate.success("申请成功！");
                    return resultDate;
                }else{
                    ResultDate resultDate=ResultDate.fail("申请失败！");
                    return resultDate;
                }
            }
        } else {
            ResultDate resultDate=ResultDate.fail("店铺名不合法！");
            return resultDate;
        }
    }
    //商家关闭店铺------>实现
    @ApiOperation(value = "关闭店铺")
    @ApiImplicitParam(name = "shopId", value = "店铺id", required = true)
    @GetMapping("shutDownShop")
    @ResponseBody
    public ResultDate shutDownShop(String shopId) {
        //删除成功返回值为1
        if(!CommonUtils.isNumeric(shopId)||!CommonUtils.isNotnull(shopId)){
            ResultDate resultDate=ResultDate.fail("参数信息有误！");
            return resultDate;
        }else if (merchantService.shutDownShopById(Integer.parseInt(shopId)) == 1) {
            //成功页面
           ResultDate resultDate=ResultDate.success("请求成功！");
            return resultDate;
        } else {
            //失败页面
            ResultDate resultDate=ResultDate.fail("店铺不存在");
            return resultDate;
        }
    }
    @ResponseBody
    @ApiOperation(value = "上架商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId",value = "店铺id",required = true),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", required = true),
            @ApiImplicitParam(name = "goodsPrice", value = "商品价格", required = true),
            @ApiImplicitParam(name = "goodsStock", value = "商品库存", required = true),
            @ApiImplicitParam(name = "goodsBrandId", value = "商品品牌", required = true),
            @ApiImplicitParam(name = "goodsTypeId", value = "商品的类型id", required = true),
    })
    @PostMapping("addGoods")
    public ResultDate addGoods(@RequestParam MultipartFile image, String shopId, String goodsName, String goodsPrice, String goodsStock, String goodsBrandId, String goodsTypeId){
        String Orignalfilename=image.getOriginalFilename();
        if(Orignalfilename.endsWith(".jpg")||Orignalfilename.endsWith(".png")||Orignalfilename.endsWith(".jpeg")||Orignalfilename.endsWith("webp")){
            String url=null;
            if(!CommonUtils.isNotnull(shopId)||!CommonUtils.isNotnull(goodsName)||!CommonUtils.isNotnull(goodsPrice)||!CommonUtils.isNotnull(goodsStock)||!CommonUtils.isNotnull(goodsBrandId)||!CommonUtils.isNotnull(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("部分参数为空");
                return resultDate;
            }else if(!CommonUtils.isNumeric(shopId)||!CommonUtils.isNumeric(goodsPrice)||!CommonUtils.isNumeric(goodsStock)||!CommonUtils.isNumeric(goodsBrandId)||!CommonUtils.isNumeric(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("参数类型错误");
                return resultDate;
            }else if(!CommonUtils.ParamIsInRange(shopId)||!CommonUtils.ParamIsInRange(goodsBrandId)||!CommonUtils.ParamIsInRange(goodsPrice)||!CommonUtils.ParamIsInRange(goodsStock)||!CommonUtils.ParamIsInRange(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("参数信息错误");
                return resultDate;
            }else{
                if(!merchantService.judgeShop(Integer.parseInt(shopId))){
                    ResultDate resultDate=ResultDate.fail("店铺信息不存在");
                    return resultDate;
                }
                if (image.isEmpty()){
                    ResultDate resultDate=ResultDate.fail("文件为空，请重新上传");
                    return resultDate;
                }
                try {
                    byte[] bytes = image.getBytes();
                    String imageName = UUID.randomUUID().toString();
                    QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
                    try {
                        //使用base64方式上传到七牛云
                        url = "http://"+qiniuUtil.put64image(bytes, imageName);
                        ResultDate resultDate=ResultDate.success("文件上传成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    ResultDate resultDate=ResultDate.fail("图片上传发生异常！");
                    return resultDate;
                }
                Goods goods=new Goods();
                goods.setGoodsBrandId(Integer.parseInt(goodsBrandId));
                goods.setGoodsImg(url);
                goods.setGoodsName(goodsName);
                goods.setGoodsPrice(Float.parseFloat(goodsPrice));
                goods.setGoodsStock(Integer.parseInt(goodsStock));
                goods.setGoodsTypeId(Integer.parseInt(goodsTypeId));
                goods.setShopId(Integer.parseInt(shopId));
                goods.setGoodsFlag(0);
                if(merchantService.addGoods(goods)==1){
                    ResultDate resultDate=ResultDate.success("请求成功！");
                    return resultDate;
                }else {
                    try {
                        qiniuCloudUtil.delete(goods.getGoodsImg());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ResultDate resultDate = ResultDate.fail("文件上传失败！");
                    return resultDate;
                }
            }
        }else {
            ResultDate resultDate=ResultDate.fail("文件类型上传有误");
            return resultDate;
        }
    }
    //<----------------------------------已经实现
    @ApiOperation(value = "下架商品")
    @ApiImplicitParam(name = "goodsId", value = "商品id", required = true)
    @GetMapping("deleteGoods")
    @ResponseBody
    public ResultDate deleteGoods(String goodsId){
        if(CommonUtils.isNumeric(goodsId)){
            int i = 0;
            try {
                i = merchantService.deleteGoods(Integer.parseInt(goodsId));
            } catch (IOException e) {
                e.printStackTrace();
                ResultDate resultDate=ResultDate.success("文件删除失败");
            }
            if(i==0){
                ResultDate resultDate=ResultDate.success("商品不存在");
                return resultDate;
            }
            return ResultDate.success("删除成功！");
        }else{
            ResultDate resultDate=ResultDate.success("参数有误");
            return resultDate;
        }
    }

    @ApiOperation(value = "更新商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsName", value = "商品名称", required = true),
            @ApiImplicitParam(name = "goodsPrice", value = "商品价格", required = true),
            @ApiImplicitParam(name = "goodsStock", value = "商品库存", required = true),
            @ApiImplicitParam(name = "goodsBrandId", value = "商品品牌", required = true),
            @ApiImplicitParam(name = "goodsTypeId", value = "商品的类型id", required = true)
    })
    @PostMapping("updateGoods")
    @ResponseBody
    public ResultDate updateGoods(@RequestParam MultipartFile image, String goodsId, String shopId, String goodsName, String goodsPrice, String goodsStock, String goodsBrandId, String goodsTypeId) {
        String Orignalfilename=image.getOriginalFilename();
        if(Orignalfilename.endsWith(".jpg")||Orignalfilename.endsWith(".png")||Orignalfilename.endsWith(".gif")){
            String url=null;
            if(!CommonUtils.isNotnull(goodsId)||!CommonUtils.isNotnull(shopId)||!CommonUtils.isNotnull(goodsName)||!CommonUtils.isNotnull(goodsPrice)||!CommonUtils.isNotnull(goodsStock)||!CommonUtils.isNotnull(goodsBrandId)||!CommonUtils.isNotnull(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("部分参数为空");
                return resultDate;
            }else if(!CommonUtils.isNumeric(goodsId)||!CommonUtils.isNumeric(shopId)||!CommonUtils.isNumeric(goodsPrice)||!CommonUtils.isNumeric(goodsStock)||!CommonUtils.isNumeric(goodsBrandId)||!CommonUtils.isNumeric(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("参数类型错误");
                return resultDate;
            }else if(!CommonUtils.ParamIsInRange(goodsId)||!CommonUtils.ParamIsInRange(shopId)||!CommonUtils.ParamIsInRange(goodsBrandId)||!CommonUtils.ParamIsInRange(goodsPrice)||!CommonUtils.ParamIsInRange(goodsStock)||!CommonUtils.ParamIsInRange(goodsTypeId)){
                ResultDate resultDate=ResultDate.fail("参数信息有误");
                return resultDate;
            }else{
                Goods goods=merchantService.queryForGoods(Integer.parseInt(goodsId));
                if(goods!=null){
                if(!merchantService.judgeShop(Integer.parseInt(shopId))){
                    ResultDate resultDate=ResultDate.fail("店铺信息不存在");
                    return resultDate;
                }
                if(!merchantService.judgeShop(Integer.parseInt(shopId))){
                    ResultDate resultDate=ResultDate.fail("店铺不存在");
                    return resultDate;
                }
                if(image!=null){
                    try {
                        qiniuCloudUtil.delete(goods.getGoodsImg());
                    } catch (IOException e) {
                        e.printStackTrace();
                        ResultDate resultDate=ResultDate.fail("文件更新异常");
                    }
                    try {
                        byte[] bytes = image.getBytes();
                        String imageName = UUID.randomUUID().toString();
                        QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
                        try {
                            //使用base64方式上传到七牛云
                            url = "http://"+qiniuUtil.put64image(bytes,imageName);
                            ResultDate resultDate=ResultDate.success("文件上传成功");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        ResultDate resultDate=ResultDate.fail("图片上传发生异常！");
                        return resultDate;
                    }
                }
                goods.setGoodsImg(url);
                goods.setGoodsBrandId(Integer.parseInt(goodsBrandId));
                goods.setGoodsName(goodsName);
                goods.setGoodsPrice(Float.parseFloat(goodsPrice));
                goods.setGoodsStock(Integer.parseInt(goodsStock));
                goods.setGoodsTypeId(Integer.parseInt(goodsTypeId));
                goods.setShopId(Integer.parseInt(shopId));
                if(merchantService.updateGoods(goods)==1){
                    ResultDate resultDate=ResultDate.success("请求成功");
                    return resultDate;
                }else {
                    ResultDate resultDate=ResultDate.fail("请求失败");
                    return resultDate;
                }
            }else{
                    ResultDate resultDate=ResultDate.fail("商品不存在");
                    return resultDate;
                }
            }
        }else {
            ResultDate resultDate=ResultDate.fail("文件类型上传有误");
            return resultDate;
        }
    }

    @ResponseBody
    @ApiOperation(value = "添加详情图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品的id",required = true),
    })
    @PostMapping("addImg")
    public ResultDate addImg(@RequestParam MultipartFile image, String goodsId){
        if(CommonUtils.isNumeric(goodsId)){
            if(image!=null){
                String goodsImg="";
                try {
                    byte[] bytes = image.getBytes();
                    String imageName = UUID.randomUUID().toString();
                    QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
                    try {
                        //使用base64方式上传到七牛云
                        goodsImg = "http://"+qiniuUtil.put64image(bytes, imageName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    ResultDate resultDate=ResultDate.fail("图片上传发生异常！");
                    return resultDate;
                }
                merchantService.addImg(new GoodsImg(null, Integer.parseInt(goodsId),goodsImg));
                ResultDate resultDate=ResultDate.success("请求成功！");
                return resultDate;
            }else{
                ResultDate resultDate=ResultDate.fail("文件为空！");
                return resultDate;
            }
        }else{
            ResultDate resultDate=ResultDate.fail("参数类型错误！");
            return resultDate;
        }
    }
    //<-===================================================已经实现>
    @GetMapping(value = "deleteImg")
    @ApiOperation("删除详情图片")
    @ResponseBody
    public ResultDate deleteImg(Integer imgId){
        if(merchantService.queryForGoodsImgByImgId(imgId)!=null){
                GoodsImg goodsImg=merchantService.queryForGoodsImgByImgId(imgId);
                merchantService.deleteImgByImgId(goodsImg.getImgId());
            try {
                qiniuCloudUtil.delete(goodsImg.getGoodsImg());
            } catch (IOException e) {
                e.printStackTrace();
                ResultDate resultDate=ResultDate.fail("删除失败");
                return resultDate;
            }
            return ResultDate.success("请求成功！");
        }else{
            ResultDate resultDate=ResultDate.fail("参数类型错误！");
            return resultDate;
        }
    }
    @GetMapping("queryForGoods")
    @ResponseBody
    @ApiOperation("查询店铺的商品")
    @ApiImplicitParam(name = "shopId",value = "店铺的id")
    public ResultDate queryForGoods(int shopId){
        List<GoodsAndShopAndGoodsTypeAndGoodsBrand> list=merchantService.queryForGoodsAll(shopId);
        ResultDate<List<GoodsAndShopAndGoodsTypeAndGoodsBrand>> resultDate=ResultDate.success("查询成功！",list);
        logger.info(String.valueOf(resultDate));
        return resultDate;
    }

    @GetMapping(value = "queryForImg")
    @ResponseBody
    public ResultDate queryForImg(String goodsId){
        logger.info("123");
        if(CommonUtils.isNumeric(goodsId)&&merchantService.queryForGoods(Integer.parseInt(goodsId))!=null){
                List<GoodsImg> list=merchantService.queryForGoodsImg(Integer.parseInt(goodsId));
                ResultDate<List<GoodsImg>> resultDate=ResultDate.success("请求成功！",list);
                return resultDate;
        }else{
            ResultDate resultDate=ResultDate.fail("参数类型错误");
            return resultDate;
        }
    }

    @GetMapping("queryForUserShop")
    @ApiImplicitParam(name = "userId",value = "用户的id")
    @ResponseBody
    public ResultDate queryForUserShop(int userId, Model model){
        List<Shop> list=merchantService.queryForUserShopById(userId);
        ResultDate resultDate=ResultDate.success("查询成功！",list);
        return resultDate;
    }

    @GetMapping("demo")
    public void demo(){
        File file=new File("D:\\Pycharm\\program\\pachong\\demo.txt");
        try {
            FileReader fileReader=new FileReader(file);
            BufferedReader bufferedReader=new BufferedReader(fileReader);
            String text=null;
            while ((text=bufferedReader.readLine())!=null){
                    merchantService.addImg(new GoodsImg(null,139,text));
            }
            file.delete();
            bufferedReader.close();
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
